package net.fdukedom.epicurus.plugin;

import java.util.Collection;
import java.util.List;

import net.fdukedom.epicurus.domain.entity.Extension;
import net.fdukedom.epicurus.domain.entity.Plugin;
import net.fdukedom.epicurus.domain.util.DomainException;
import net.fdukedom.epicurus.domain.util.PluginHelper;
import net.fdukedom.epicurus.messaging.MessageDispatcher;
import net.fdukedom.epicurus.resource.ResourceDispatcher;
import net.fdukedom.epicurus.security.AccessChecker;
import net.fdukedom.epicurus.tools.logging.Logger;
import net.fdukedom.epicurus.tools.logging.WriterId;

public class PluginRegistrar {
    /**
     * Registers plug-ins in all dispatchers.
     *
     * @param plugins plug-ins to be registered.
     */
    static public void register(Collection<Plugin> plugins) {
        PluginHelper pluginHelper = PluginHelper.getInstance();
        ResourceDispatcher resourceDispatcher = ResourceDispatcher.getInstance();
        AccessChecker accessChecker = AccessChecker.getInstance();
        for (Plugin plugin : plugins) {
            try {
                MessageDispatcher.getInstance().registerReciever(plugin.getMessageTypes(),
                        plugin.getName(), pluginHelper.getMessageRecipient(plugin));
                resourceDispatcher.registerPlugin(plugin);
                resourceDispatcher.registerPages(plugin.getPages());
                resourceDispatcher.registerExtensionPoints(plugin.getExtensionPoints());
                accessChecker.addRules(plugin.getAccessRules());
                for (Extension extension : plugin.getExtensions()) {
                    resourceDispatcher.registerExtension(extension.getExtensionPointName(), pluginHelper.getExtension(extension));
                }
            } catch (DomainException e) {
                Logger.getInstance(WriterId.PLUGIN_LOADER).logError("Plug-in registration exception. Plug-in: " + plugin.getName() + ". Exception message: " + e.getMessage());
            }
        }
    }
}
